package com.longer.demo.biz.controller;

import com.alibaba.druid.util.StringUtils;
import com.longer.demo.biz.controller.model.UserVO;
import com.longer.demo.biz.service.UserService;
import com.longer.demo.biz.service.model.UserModel;
import com.longer.demo.framework.controller.BaseController;
import com.longer.demo.framework.error.BusinessError;
import com.longer.demo.framework.error.BusinessException;
import com.longer.demo.framework.error.CommonError;
import com.longer.demo.framework.reponse.CommonResponse;
import com.longer.demo.framework.util.EncrytUtils;
import io.netty.handler.codec.base64.Base64Encoder;
import org.apache.catalina.User;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @program: demo
 * @description:
 * @author: SunBiaoLong
 * @create: 2019-01-10 13:49
 **/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {


	@Autowired
	private HttpServletRequest httpServletRequest;


	@Autowired(required = false)
	private UserService userService;

	@GetMapping("/user")
	public CommonResponse getUser() throws BusinessException {
		UserModel userModel = userService.getUserModelById(1);
		if (userModel == null) {
			throw new BusinessException(BusinessError.USER_NOT_EXIST);
		}
		return CommonResponse.create(convertFromModel(userModel));
	}

	/**
	 * 用户获取otp短信接口
	 * @return
	 */
	@PostMapping(value = "/otp",consumes = {CONTENT_TYPE_FORMED})
	@ResponseBody
	public CommonResponse getOtp(@RequestParam(name = "phone") String phone){
		//按照一定的规则生成otp验证码
		Random random = new Random();
		int randomInt = random.nextInt(99999);
		randomInt += 100000;
		String otpCode=String.valueOf(randomInt);

		//将otp验证码同对应的用户的手机号关联 使用httpsession绑定手机号和otpcode
		httpServletRequest.getSession().setAttribute(phone,otpCode);

		//将otp验证码通过短信通道发送给用户,省略...
		System.out.println("phone.."+phone);
		System.out.println("otpcode.."+otpCode);


		return CommonResponse.create(otpCode);
	}


	private UserVO convertFromModel(UserModel userModel) {
		if (userModel == null) {
			return null;
		}
		UserVO userVO = new UserVO();
		BeanUtils.copyProperties(userModel, userVO);
		return userVO;
	}

	/**
	 * 跨域问题已经解决--在过滤器阶段,,,前端也做了过滤,两次ajax发送的跨域授信
	 * 前端使用的jquery的ajax,使用  xhrFields:{withCredentials:true},支持跨域(保持session)
	 * @param name
	 * @param phone
	 * @param otpCode
	 * @param gender
	 * @param password
	 * @param age
	 * @return
	 * @throws BusinessException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */

	@PostMapping(value = "/register",consumes = {CONTENT_TYPE_FORMED})
	public CommonResponse register(@RequestParam(name = "name")String name,
	                               @RequestParam(name = "phone") String phone,
	                               @RequestParam(name = "otpCode") String otpCode,
	                               @RequestParam(name = "gender") Byte gender,
	                               @RequestParam(name = "password") String  password,
	                               @RequestParam(name = "age") Integer age) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
		//验证手机验证码
		String sessionOtpCode = (String) httpServletRequest.getSession().getAttribute(phone);
		//设计到跨域--前后端都要处理
		System.out.println(otpCode);
		if (!StringUtils.equals(otpCode,sessionOtpCode)){
			throw new BusinessException(BusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不通过");
		}
		UserModel userModel = new UserModel();
		userModel.setName(name);
		userModel.setGender(gender);
		userModel.setAge(age);
		userModel.setPhone(phone);
		userModel.setRegisterMode("byphone");
		userModel.setEncryptPassword(EncrytUtils.encrypt(password));
		userService.register(userModel);
		//用户注册流程
		return CommonResponse.create("注册成功");
	}


	@PostMapping("/login")
	public CommonResponse login(@RequestParam(name = "phone") String phone,@RequestParam(name = "password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
		//验证是否为空
		if (org.apache.commons.lang3.StringUtils.isEmpty(phone)|| org.apache.commons.lang3.StringUtils.isEmpty(password)){
			throw new BusinessException(BusinessError.PARAMETER_VALIDATION_ERROR);
		}
		UserModel userModel = userService.validate(phone, EncrytUtils.encrypt(password));
		httpServletRequest.getSession().setAttribute("isLOGIN","true");
		httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
		//校验
		return CommonResponse.create("登录成功");
	}


}
